package net.worldscale.xp.wspr.impl;

import net.worldscale.xp.wspr.Debug;
import java.io.PrintStream;
import java.util.Enumeration;
import java.util.Hashtable;
import net.worldscale.xp.wspr.Module;
import net.worldscale.xp.wspr.ModuleFactory;
import net.worldscale.xp.wspr.ModuleKey;
import net.worldscale.xp.wspr.ModuleManager;

class ImplModuleManager extends ModuleManager {

    public ImplModuleManager() {
    }
    private final Hashtable<ModuleKey, ModuleFactory> ht = new Hashtable<ModuleKey, ModuleFactory>();

    @Override
    public void printModuleList() {
        this.printModuleList(System.out);
    }

    @Override
    public void printModuleList(PrintStream ps) {
        ps.println("Module List:");
        ps.println("    name | version | class");
        ps.println("    ----------------------");
        final Enumeration<ModuleFactory> enu = ht.elements();
        for (; enu.hasMoreElements();) {
            final ModuleFactory mf = enu.nextElement();
            ps.println("    " + mf.getInfo().getName() + " | " + mf.getInfo().getVersion()
                    + " | " + mf.getInfo().getClass().getName());
        }
    }

    @Override
    public void registerFactory(ModuleFactory mf) {
        ht.put(mf.getInfo().getKey(), mf);
    }

    @Override
    public ModuleFactory getFactory(ModuleKey key) {
        final ModuleFactory ret = ht.get(key);
        if (ret == null) {
            System.out.println("There is no implements for the module of " + key);
            Debug.printCallStack();
        }
        return ret;
    }

    @Override
    public Module createModule(ModuleKey key) {
        try {
            return this.getFactory(key).createInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
